package com.fs.base.excel.view;

import com.fs.base.excel.ExcelOptions;
import com.fs.base.excel.ExcelUtils;
import com.fs.base.excel.ExcelWriterUtils;
import com.fs.base.utils.CommonUtils;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsView;

/**
 * 97-2003版Excel视图
 * <p>Created by Raofeicheng on 2017/12/6.</p>
 * @author Raofeicheng
 * @version 1.0
 */
@Getter
@Setter
@NoArgsConstructor
public class XlsView extends AbstractXlsView {

	public XlsView(Collection<Object> data) {
		this(data.iterator());
	}

	public XlsView(Iterator<Object> data) {
		setData(data);
	}

	/**
	 * 输出excel内容
	 * @param workbook excel对象
	 */
	protected void buildExcelDocument(Map<String, Object> model, Workbook workbook
		, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null == opts) opts = ExcelUtils.getOptions(request);
		String fileName = StringUtils.trimToEmpty(opts.getFilename());
		if (StringUtils.isBlank(fileName)) fileName = "导出数据";
		if (this instanceof XlsxStreamingView && !StringUtils.endsWithIgnoreCase(fileName, ".xlsx")) fileName += ".xlsx";
		if (!(this instanceof XlsxStreamingView) && !StringUtils.endsWithIgnoreCase(fileName, ".xls")) fileName += ".xls";
		response.setHeader("Content-Disposition", "attachment;filename=" + CommonUtils.encodeFilename(fileName, request));
		ExcelWriterUtils.write(workbook, data, opts);
	}

	private ExcelOptions opts;
	private Iterator<Object> data;

}
